//
//  HomeViewController.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/23.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

private let JustinStatusCellID = "JustinStatusCellID"
private let JustinStatusTipCellID = "JustinStatusTipCellID"

class HomeViewController: RootViewController {
    // MARK: - 监听方法
    @objc private func reachabilityChanged() {
        self.tableView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Bottom)
    }
    
    // MARK:- 懒加载数组
    //拿到VM进行操作
    private lazy var statusList = [StatusViewModel]()
    
    override func viewDidLoad() {
        
        setupRefreshControl()
        
        super.viewDidLoad()
        
        prepareTableView()
        
        visitorView?.setupInfo(nil, message: "关注一些人，回这里看看有什么惊喜")
        
        // MARK:- 添加通知观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged", name: JustinWeiBoNetworkReachabilityNotification, object: nil)
        
    }
    // MARK:- 收到内存警告
    override func didReceiveMemoryWarning() {
        //需要进行判断当前的数据是否显示在屏幕上，不能销毁显示在当前屏幕上的数据
        if self.view.window == nil {
            
            self.statusList.removeAll()
            
            self.tableView?.reloadData()
        }
    }
    
    // MARK:- 加载数据
    override func loadData() {
        
        guard let refreshControl = refreshControl else {
            return
        }
        
        let isPullup = refreshControl.isPullupRefresh ?? false
        
        refreshControl.beginRefreshing()
        
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
        NetworkTools.sharedTools.loadStatus(since_id, max_id: max_id) { (result) -> () in
            
            self.refreshControl?.endRefreshing()
            
            guard let result = result else {
                print("你的网络不给力")
                return
            }
            
            guard let array = result["statuses"] as? [[String: AnyObject]] else {
                print("网络数据出错")
                return
            }
            
            // MARK:- 字典转模型
            var arrM = [StatusViewModel]()
            
            for dict in array {
                arrM.append(StatusViewModel(status: Status.yy_modelWithJSON(dict)!))
            }
            
            print("刷新\(arrM.count)条")
            
            if isPullup {
                self.statusList += arrM
            } else {
                self.statusList = arrM + self.statusList
            }
            
            self.tableView?.reloadData()
            
        }
    }

    
}

// MARK: - 设置tableview的基本属性和注册cell
extension HomeViewController {
    
    private func prepareTableView() {
    
        guard let tableView = tableView else {
            return
        }
        
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: JustinStatusCellID)
        tableView.registerClass(StatusTipCell.self, forCellReuseIdentifier: JustinStatusTipCellID)
        
        //设置预估行高以及使用自动计算行高，才能执行自动计算行高
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //取消表格的分隔线
        tableView.separatorStyle = .None
    }
    
}

// MARK:- 数据源方法
extension HomeViewController {
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return NetworkTools.sharedTools.reachable ? 0 : 1
        }
        
        return statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //当section为零时，显示唯一的cell来显示无法连接网络
        if indexPath.section == 0 {
            return tableView.dequeueReusableCellWithIdentifier(JustinStatusTipCellID, forIndexPath: indexPath)
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(JustinStatusCellID, forIndexPath: indexPath) as! StatusCell
        
        cell.viewModel = statusList[indexPath.row]
        
        cell.textLabel?.hidden = true
        
//        print("\(statusList[indexPath.row].status.text)")
        
        return cell
    }
}